<?php
/**
 * Created by PhpStorm.
 * User: zanboon-201
 * Date: 2019/3/20
 * Time: 9:44
 */

namespace app\generate\model;
use think\Db;
use think\exception\PDOException;
use think\Model;
use think\facade\Config;


class Index extends Model
{
    //数据库操作
    public function pdo_exec_sql($query,$dbname = null){
        $dbname = ';dbname='.$dbname;
        if (empty($dbname)){
            $dbname = '';
        }
        $database = Config::get('database.');
        try{
            $dbh = new \PDO( 'mysql:host='.$database['hostname'].';port='.$database['hostport'].$dbname, $database['username'], $database['password'], array(\PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8"));
        } catch (PDOException $e) {
            return false;
        }
        $res = $dbh->exec($query);
        if ($res===false){
            return false;
        }
        return true;
    }

    //创建generate的数据库
    public function create_generate_database(){
            $query = <<<SQL
        CREATE DATABASE IF NOT EXISTS zb_generate character set utf8 COLLATE utf8_general_ci;
        USE zb_generate;
        CREATE TABLE IF NOT EXISTS `tp_controller` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `table_id` int(11) NOT NULL DEFAULT '0',
          `function_title` varchar(255) NOT NULL DEFAULT '' COMMENT '接口标题',
          `function_desc` varchar(255) NOT NULL DEFAULT '' COMMENT '接口说明',
          `person_name` varchar(255) NOT NULL DEFAULT '' COMMENT '负责人',
          `function_name` varchar(255) NOT NULL DEFAULT '' COMMENT '方法名',
          `method_type` varchar(255) NOT NULL DEFAULT '' COMMENT '表单方法',
          `function_data` text NOT NULL COMMENT '接口和方法（json）',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_field` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `table_id` int(11) NOT NULL DEFAULT '0' COMMENT '表ID',
          `comment` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',
          `name` varchar(255) NOT NULL DEFAULT '' COMMENT '名称',
          `type` varchar(255) NOT NULL DEFAULT 'VarChar' COMMENT '类型',
          `length` varchar(255) NOT NULL DEFAULT '',
          `default` varchar(255) NOT NULL DEFAULT '',
          `not_null` tinyint(3) NOT NULL DEFAULT '1',
          `enum` text NOT NULL COMMENT '枚举注释（json格式）',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_group` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `name` varchar(255) DEFAULT NULL COMMENT '分组名称',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_model` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `db_name` varchar(255) DEFAULT NULL COMMENT '数据库名称',
          `model_name` varchar(255) DEFAULT NULL COMMENT '模块名称',
          `model_namespace` varchar(255) DEFAULT NULL COMMENT '模块命名空间',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_person` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `name` varchar(255) DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_table` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `group_id` int(11) NOT NULL DEFAULT '0' COMMENT '分组ID',
          `model_id` int(11) NOT NULL DEFAULT '0' COMMENT '模型ID',
          `person_id` int(11) NOT NULL DEFAULT '0' COMMENT '负责人ID',
          `table_prefix` varchar(255) NOT NULL DEFAULT 'tp_' COMMENT '前缀',
          `table_name` varchar(255) NOT NULL DEFAULT '' COMMENT '表名称',
          `engine` varchar(255) NOT NULL DEFAULT 'MyISAM' COMMENT '数据库引擎',
          `table_title` varchar(255) NOT NULL DEFAULT '' COMMENT '表名称（中文）',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_validate_field` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `table_id` int(11) NOT NULL DEFAULT '0' COMMENT '表id',
          `field_id` int(11) NOT NULL DEFAULT '0' COMMENT '字段id',
          `validate` text NOT NULL COMMENT '验证器（json）',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        
        CREATE TABLE IF NOT EXISTS `tp_validate_scene` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `table_id` int(11) NOT NULL DEFAULT '0' COMMENT '表id',
          `name` varchar(255) NOT NULL DEFAULT '' COMMENT '场景名称',
          `v_field_id` varchar(255) NOT NULL DEFAULT '' COMMENT '验证字段id',
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

        CREATE DATABASE IF NOT EXISTS zb_login character set utf8 COLLATE utf8_general_ci;
        USE zb_login;
        CREATE TABLE IF NOT EXISTS  `tp_account` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `account_name` varchar(255) DEFAULT NULL COMMENT '登录名',
          `password` varchar(255) DEFAULT NULL COMMENT '密码',
          `openId` varchar(255) DEFAULT NULL,
          `islock` tinyint(3) NOT NULL DEFAULT '0' COMMENT '是否锁定（0-正常；1-锁定）',
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
        INSERT ignore INTO `tp_account` VALUES (1,'admin','e10adc3949ba59abbe56e057f20f883e',NULL,0),(2,'lcm','e10adc3949ba59abbe56e057f20f883e',NULL,0);

        CREATE TABLE `tp_token` (
          `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
          `account_id` int(11) DEFAULT NULL COMMENT '账号id',
          `token` varchar(50) DEFAULT NULL COMMENT 'token',
          `expires_in` int(11) DEFAULT NULL COMMENT '有效时间',
          `create_time` int(11) DEFAULT NULL COMMENT '创建时间',
          `end_time` int(11) DEFAULT NULL COMMENT '过期时间',
          `sys_ip` varchar(255) DEFAULT NULL COMMENT '登录ip',
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

        CREATE DATABASE IF NOT EXISTS zb_user character set utf8 COLLATE utf8_general_ci;
        USE zb_user;
        CREATE TABLE IF NOT EXISTS `tp_address` (
          `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
          `userID` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
          `name` varchar(50) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '收货姓名',
          `mobile` varchar(50) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '收货手机',
          `address` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '地址',
          `isDefault` tinyint(3) NOT NULL DEFAULT '0' COMMENT '是否为默认地址',
          `isDelete` tinyint(3) NOT NULL DEFAULT '0' COMMENT '是否删除',
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='地址';
        
        CREATE TABLE IF NOT EXISTS `tp_admin_user` (
          `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
          `account_id` int(11) NOT NULL DEFAULT '0' COMMENT '账号id',
          `nickname` varchar(255) DEFAULT NULL COMMENT '昵称',
          `head_img` varchar(255) DEFAULT NULL COMMENT '头像地址',
          `status` tinyint(1) DEFAULT '1' COMMENT '状态（0不可用；1正常）',
          PRIMARY KEY (`id`,`account_id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
        
        INSERT ignore INTO `tp_admin_user` VALUES (1,1,'sxw',NULL,1),(2,2,'lcm','',1);
        
        CREATE TABLE `tp_user` (
          `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
          `account_id` int(11) NOT NULL DEFAULT '0' COMMENT '账号id',
          `nickName` varchar(50) DEFAULT NULL,
          `avatarUrl` varchar(255) DEFAULT NULL COMMENT '头像',
          `status` tinyint(1) DEFAULT '1' COMMENT '状态（0不可用；1正常）',
          `gender` varchar(255) DEFAULT NULL COMMENT '性别',
          `country` varchar(255) DEFAULT NULL COMMENT '国家',
          `province` varchar(255) DEFAULT NULL COMMENT '省份',
          `city` varchar(255) DEFAULT NULL COMMENT '城市',
          `language` varchar(255) DEFAULT NULL COMMENT '语言',
          PRIMARY KEY (`id`,`account_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        
        CREATE DATABASE IF NOT EXISTS zb_admin_auth character set utf8 COLLATE utf8_general_ci;
        USE zb_admin_auth;
        CREATE TABLE IF NOT EXISTS `tp_shop_admin_page` (
          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `path` varchar(255) DEFAULT NULL COMMENT 'vue路由',
          `component` varchar(255) DEFAULT NULL COMMENT '组件',
          `redirect` varchar(255) DEFAULT NULL COMMENT '重定向地址',
          `alwaysShow` tinyint(1) DEFAULT NULL COMMENT '一直显示根路由',
          `hidden` tinyint(3) NOT NULL DEFAULT '0' COMMENT '不在侧边栏线上',
          `ismain` tinyint(3) DEFAULT '1' COMMENT '是否是主菜单',
          `title` varchar(255) DEFAULT NULL COMMENT '设置该路由在侧边栏和面包屑中展示的名字',
          `icon` varchar(255) DEFAULT NULL COMMENT '设置该路由的图标',
          `nocache` tinyint(1) DEFAULT '1' COMMENT '如果设置为true ,则不会被 <keep-alive> 缓存(默认 false)',
          `name` varchar(255) DEFAULT NULL COMMENT '设定路由的名字，一定要填写不然使用<keep-alive>时会出现各种问题',
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
        INSERT ignore INTO `tp_shop_admin_page` VALUES (1,'','Layout','/shop_admin_auth/admin_page/customTreeTable',1,0,1,'权限管理','password',1,'shop_admin_auth'),(2,'/shop_admin_auth/admin_page/customTreeTable','shop_admin_auth/admin_page/customTreeTable','',1,0,0,'权限管理',NULL,1,'admin_page'),(3,'/shop_admin_auth/shop_role/index','shop_admin_auth/shop_role/index',NULL,1,0,0,'角色管理',NULL,1,'shop_role'),(4,'/user/admin_user/index','user/admin_user/index','',1,0,0,'管理员管理','',1,'admin_user');
        
        CREATE TABLE IF NOT EXISTS `tp_shop_admin_page_role` (
          `shop_page_id` int(11) NOT NULL COMMENT '页面页面id',
          `shop_role_id` int(11) NOT NULL COMMENT '角色id',
          PRIMARY KEY (`shop_page_id`,`shop_role_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='关系：多对多';
        INSERT ignore INTO `tp_shop_admin_page_role` VALUES (1,1),(2,1),(3,1),(3,2),(4,1),(4,2);
        
        CREATE TABLE IF NOT EXISTS `tp_shop_admin_page_tree` (
          `depth` int(11) DEFAULT NULL,
          `left` int(11) DEFAULT NULL,
          `parent_id` int(11) DEFAULT NULL,
          `right` int(11) DEFAULT NULL,
          `root_id` int(11) DEFAULT NULL,
          `son_id` int(11) DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        INSERT ignore INTO `tp_shop_admin_page_tree` VALUES (0,9,0,9,0,0),(0,1,1,8,0,1),(1,1,0,8,0,1),(0,2,2,3,0,2),(1,2,1,3,0,2),(2,2,0,3,0,2),(0,4,3,5,0,3),(1,4,1,5,0,3),(2,4,0,5,0,3),(0,6,4,7,0,4),(1,6,1,7,0,4),(2,6,0,7,0,4);
        
        CREATE TABLE IF NOT EXISTS `tp_shop_admin_page_tree_move_to` (
          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `son_id` int(11) DEFAULT NULL,
          `parent_id` int(11) DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
        INSERT ignore INTO `tp_shop_admin_page_tree_move_to` VALUES (1,6,3),(2,1,0),(3,2,1),(4,3,0),(5,3,1),(6,4,1);
        
        CREATE TABLE IF NOT EXISTS `tp_shop_admin_role` (
          `account_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `shop_role_id` int(11) DEFAULT NULL,
          PRIMARY KEY (`account_id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
        INSERT ignore INTO `tp_shop_admin_role` VALUES (1,1),(2,1);
        
        CREATE TABLE IF NOT EXISTS `tp_shop_role` (
          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(255) DEFAULT NULL COMMENT '名称，管理员',
          `role` varchar(255) DEFAULT NULL COMMENT '标签：如admin',
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
        INSERT ignore INTO `tp_shop_role` VALUES (1,'管理员','admin'),(2,'operator','operator');

        

SQL;
        return $this->pdo_exec_sql($query);
    }


    //接口一键生成增删改查
    public function auto_create_function($table_id){
        $table = Db::table('zb_generate.tp_table')->find($table_id);
        $person = Db::table('zb_generate.tp_person')->find($table['person_id']);
        $field_list = Db::table('zb_generate.tp_field')->where('table_id','=',$table_id)->select();
        $v_scene_list = $this->create_validate($table_id);

        $data = [
            [
                'table_id'=>$table_id,
                'function_title'=>'插入记录',
                'function_desc'=>'插入'.$table['table_title'].'数据',
                'person_name'=>$person['name'],
                'function_name'=>'add',
                'method_type'=>'post',
                'function_data'=>$this->create_insert_data($table,$field_list,$v_scene_list)
            ],
            [
                'table_id'=>$table_id,
                'function_title'=>'获取列表数据（paginate）',
                'function_desc'=>'获取'.$table['table_title'].'的列表数据（分页）',
                'person_name'=>$person['name'],
                'function_name'=>'get_list',
                'method_type'=>'*',
                'function_data'=>$this->create_get_list_data($table,$field_list)
            ],
            [
                'table_id'=>$table_id,
                'function_title'=>'获取列表数据（select）',
                'function_desc'=>'获取'.$table['table_title'].'的列表数据（无分页）',
                'person_name'=>$person['name'],
                'function_name'=>'get_select',
                'method_type'=>'*',
                'function_data'=>$this->create_get_select_data($table,$field_list)
            ],
            [
                'table_id'=>$table_id,
                'function_title'=>'获取单条数据',
                'function_desc'=>'根据ID获取'.$table['table_title'].'的指定记录',
                'person_name'=>$person['name'],
                'function_name'=>'info',
                'method_type'=>'*',
                'function_data'=>$this->create_info_data($table,$field_list,$v_scene_list)
            ],
            [
                'table_id'=>$table_id,
                'function_title'=>'更新记录',
                'function_desc'=>'根据ID更新'.$table['table_title'].'指定记录的数据',
                'person_name'=>$person['name'],
                'function_name'=>'edit',
                'method_type'=>'post',
                'function_data'=>$this->create_update_data($table,$field_list,$v_scene_list)
            ],
            [
                'table_id'=>$table_id,
                'function_title'=>'按条件删除记录',
                'function_desc'=>'按条件删除'.$table['table_title'].'的数据',
                'person_name'=>$person['name'],
                'function_name'=>'delete',
                'method_type'=>'post',
                'function_data'=>$this->create_delete_data($table,$field_list,$v_scene_list)
            ],
        ];
        return Db::table('zb_generate.tp_controller')->insertAll($data);
    }

    //创建场景
    public function create_validate($table_id){
        $api_model = new \app\generate\model\Api();
        $api_model->auto_insert_validate($table_id);

        $validate_field_list = $api_model->get_v_field_list($table_id);

        $data = [
            [
                'table_id'=>$table_id,
                'name'=>'all_field',
                'v_field_id'=>''
            ],
            [
                'table_id'=>$table_id,
                'name'=>'except_id',
                'v_field_id'=>''
            ],
            [
                'table_id'=>$table_id,
                'name'=>'only_id',
                'v_field_id'=>''
            ]
        ];
        $temp_all='';
        $temp_except='';
        $temp_id='';
        foreach ($validate_field_list as $k=>$v){
            if ($v['name']=='id'){
                $temp_id=$v['id'];
            }
            if ($v['name']!='id'){
                if ($temp_except!=''){
                    $temp_except.=",";
                }
                $temp_except.=$v['id'];
            }
            if ($temp_all!=''){
                $temp_all.=",";
            }
            $temp_all.=$v['id'];
        }
        $data[0]['v_field_id']=$temp_all;
        $data[1]['v_field_id']=$temp_except;
        $data[2]['v_field_id']=$temp_id;
        Db::table('zb_generate.tp_validate_scene')->insertAll($data);
        return $api_model->get_validate_scene_all_data($table_id);
    }

    //insert的数据生成
    public function create_insert_data($table,$field_list,$v_scene_list){
        $res = [];

        $input= [
            'type'=>'input',
            'return_name'=>'input',
            'data'=>[]
        ];
        foreach ($field_list as $k=>$v){
            if ($v['name'] == 'id'){
                continue;
            }
            $input_data=[
                'is_back'=>false,
                'is_hide'=>true,
                'table_name'=>$table['table_prefix'].$table['table_name'],
                'comment'=>$v['comment'],
                'field_name'=>$v['name'],
                'field_type'=>$v['type'],
                'enum'=>json_decode($v['enum'],true)
            ];
            array_push($input['data'],$input_data);
        }
        array_push($res,$input);

        $validate = [
            'type'=>'validate',
            'input_name'=>'input',
            'return_name'=>'validate',
            'validate'=>[]
        ];
        foreach ($v_scene_list as $k=>$v) {
            if ($v['name']=='except_id'){
                $validate['validate'] = $v;
                break;
            }
        }
        array_push($res,$validate);

        $insert = [
            'type'=>'insert',
            'table_name'=>$table['table_prefix'].$table['table_name'],
            'return_name'=>'insert_res',
            'data'=>[]
        ];
        foreach ($input['data'] as $k=>$v){
            $insert_data=[
                "table_name"=>$table['table_prefix'].$table['table_name'],
                "comment"=>$v['comment'],
                "field_name"=>$v['field_name'],
                "field_type"=>$v['field_type'],
                "root_var_name"=>"input",
                "root_field_name"=>$v['field_name'],
                "enum"=>$v['enum']
            ];
            array_push($insert['data'],$insert_data);
        }
        array_push($res,$insert);

        return json_encode($res);
    }

    //get_list的数据生成
    public function create_get_list_data($table,$field_list){
        $res = [];

        $input= [
            'type'=>'input',
            'return_name'=>'input',
            'data'=>[]
        ];
        foreach ($field_list as $k=>$v){
            $input_data=[
                'is_back'=>false,
                'is_hide'=>true,
                'table_name'=>$table['table_prefix'].$table['table_name'],
                'comment'=>$v['comment'],
                'field_name'=>$v['name'],
                'field_type'=>$v['type'],
                'enum'=>json_decode($v['enum'],true)
            ];
            array_push($input['data'],$input_data);
        }
        array_push($res,$input);

        $select = [
            'type'=>'select',
            'select_type'=>'paginate',
            'table_name'=>$table['table_prefix'].$table['table_name'],
            'alias'=>'',
            'data'=>[],
            'join'=>[],
            'condition'=>[],
            'where'=>[],
            'return_name'=>'select_res',
        ];
        foreach ($field_list as $k=>$v){
            $condition = '=';
            if ($v['type']=='VarChar' | $v['type']=='Text'){
                $condition = 'like';
            }
            $temp_where=[
                "table_name"=>$table['table_prefix'].$table['table_name'],
                "comment"=>$v['comment'],
                "field_name"=>$v['name'],
                "field_type"=>$v['type'],
                "condition"=>$condition,
                "con_var_name"=>"input",
                "con_field_name"=>$v['name'],
                "enum"=>$v['enum']
            ];
            array_push($select['where'],$temp_where);
        }

        array_push($res,$select);
        return json_encode($res);
    }
    //get_select的数据生成
    public function create_get_select_data($table,$field_list){
        $res = [];

        $input= [
            'type'=>'input',
            'return_name'=>'input',
            'data'=>[]
        ];
        foreach ($field_list as $k=>$v){
            $input_data=[
                'is_back'=>false,
                'is_hide'=>true,
                'table_name'=>$table['table_prefix'].$table['table_name'],
                'comment'=>$v['comment'],
                'field_name'=>$v['name'],
                'field_type'=>$v['type'],
                'enum'=>json_decode($v['enum'],true)
            ];
            array_push($input['data'],$input_data);
        }
        array_push($res,$input);

        $select = [
            'type'=>'select',
            'select_type'=>'select',
            'table_name'=>$table['table_prefix'].$table['table_name'],
            'alias'=>'',
            'data'=>[],
            'join'=>[],
            'condition'=>[],
            'where'=>[],
            'return_name'=>'select_res',
        ];
        foreach ($field_list as $k=>$v){
            $condition = '=';
            if ($v['type']=='VarChar' | $v['type']=='Text'){
                $condition = 'like';
            }
            $temp_where=[
                "table_name"=>$table['table_prefix'].$table['table_name'],
                "comment"=>$v['comment'],
                "field_name"=>$v['name'],
                "field_type"=>$v['type'],
                "condition"=>$condition,
                "con_var_name"=>"input",
                "con_field_name"=>$v['name'],
                "enum"=>$v['enum']
            ];
            array_push($select['where'],$temp_where);
        }

        array_push($res,$select);
        return json_encode($res);
    }
    //info的数据生成
    public function create_info_data($table,$field_list,$v_scene_list){
        $res = [];
        $input= [
            'type'=>'input',
            'return_name'=>'input',
            'data'=>[]
        ];
        foreach ($field_list as $k=>$v){
            if ($v['name'] == 'id'){
                $input_data=[
                    'is_back'=>false,
                    'is_hide'=>true,
                    'table_name'=>$table['table_prefix'].$table['table_name'],
                    'comment'=>$v['comment'],
                    'field_name'=>$v['name'],
                    'field_type'=>$v['type'],
                    'enum'=>json_decode($v['enum'],true)
                ];
                array_push($input['data'],$input_data);
                break;
            }
        }
        array_push($res,$input);

        $validate = [
            'type'=>'validate',
            'input_name'=>'input',
            'return_name'=>'validate',
            'validate'=>[]
        ];
        foreach ($v_scene_list as $k=>$v) {
            if ($v['name']=='only_id'){
                $validate['validate'] = $v;
                break;
            }
        }
        array_push($res,$validate);

        $select = [
            'type'=>'select',
            'select_type'=>'find',
            'table_name'=>$table['table_prefix'].$table['table_name'],
            'alias'=>'',
            'data'=>[],
            'join'=>[],
            'condition'=>[],
            'where'=>[
                [
                    "table_name"=>$table['table_prefix'].$table['table_name'],
                    "comment"=>"id",
                    "field_name"=>"id",
                    "field_type"=>"Int",
                    "condition"=>"=",
                    "con_var_name"=>"input",
                    "con_field_name"=>"id",
                    "enum"=>$input['data'][0]['enum']
                ]
            ],
            'return_name'=>'select_res',
        ];
        array_push($res,$select);
        return json_encode($res);
    }
    //update的数据生成
    public function create_update_data($table,$field_list,$v_scene_list){
        $res = [];
        $input= [
            'type'=>'input',
            'return_name'=>'input',
            'data'=>[]
        ];
        foreach ($field_list as $k=>$v){
            $input_data=[
                'is_back'=>false,
                'is_hide'=>true,
                'table_name'=>$table['table_prefix'].$table['table_name'],
                'comment'=>$v['comment'],
                'field_name'=>$v['name'],
                'field_type'=>$v['type'],
                'enum'=>json_decode($v['enum'],true)
            ];
            array_push($input['data'],$input_data);
        }
        array_push($res,$input);

        $validate = [
            'type'=>'validate',
            'input_name'=>'input',
            'validate'=>[],
            'return_name'=>'validate'
        ];
        foreach ($v_scene_list as $k=>$v) {
            if ($v['name']=='all_field'){
                $validate['validate'] = $v;
                break;
            }
        }
        array_push($res,$validate);

        $update = [
            'type'=>'update',
            'table_name'=>$table['table_prefix'].$table['table_name'],
            'data'=>[],
            'where'=>[
                [
                    "table_name"=>$table['table_prefix'].$table['table_name'],
                    "comment"=>"id",
                    "field_name"=>"id",
                    "field_type"=>"Int",
                    "condition"=>"=",
                    "con_var_name"=>"input",
                    "con_field_name"=>"id",
                    "enum"=>[]
                ]
            ],
            'return_name'=>'update_res',
        ];
        foreach ($field_list as $k=>$v){
            if ($v['name']!=='id'){
                $update_data=[
                    'table_name'=>$table['table_prefix'].$table['table_name'],
                    'comment'=>$v['comment'],
                    'field_name'=>$v['name'],
                    'field_type'=>$v['type'],
                    "root_var_name"=>"input",
                    "root_field_name"=>$v['name'],
                    'enum'=>json_decode($v['enum'],true)
                ];
                array_push($update['data'],$update_data);
            }
        }

        array_push($res,$update);
        return json_encode($res);
    }
    //delete的数据生成
    public function create_delete_data($table,$field_list,$v_scene_list){
        $res = [];
        $input= [
            'type'=>'input',
            'return_name'=>'input',
            'data'=>[]
        ];
        foreach ($field_list as $k=>$v){
            $input_data=[
                'is_back'=>false,
                'is_hide'=>true,
                'table_name'=>$table['table_prefix'].$table['table_name'],
                'comment'=>$v['comment'],
                'field_name'=>$v['name'],
                'field_type'=>$v['type'],
                'enum'=>json_decode($v['enum'],true)
            ];
            array_push($input['data'],$input_data);
        }
        array_push($res,$input);
        $delete = [
            'type'=>'delete',
            'table_name'=>$table['table_prefix'].$table['table_name'],
            'where'=>[],
            'return_name'=>'delete_res',
        ];
        foreach ($field_list as $k=>$v){
            $temp_where=[
                "table_name"=>$table['table_prefix'].$table['table_name'],
                "comment"=>$v['comment'],
                "field_name"=>$v['name'],
                "field_type"=>$v['type'],
                "condition"=>'=',
                "con_var_name"=>"input",
                "con_field_name"=>$v['name'],
                "enum"=>$v['enum']
            ];
            array_push($delete['where'],$temp_where);
        }

        array_push($res,$delete);
        return json_encode($res);
    }

    //字段检测
    public function check_field($table_id){
        $table = Db::table('zb_generate.tp_table')->find($table_id);
        $model = Db::table('zb_generate.tp_model')->find($table['model_id']);
        if (!$table | !$model){
            return $table;
        }
        $generate_field = Db::table('zb_generate.tp_field')->where('table_id','=',$table_id)->select();
        $database_field = Db::table('INFORMATION_SCHEMA.Columns')
            ->where('table_schema','=','zb_'.$model['db_name'])
            ->where('table_name','=',$table['table_prefix'].''.$table['table_name'])->select();

        $t_g_f = $generate_field;
        $t_d_f = $database_field;
        //不同的字段
        $different_field = [];
        for ($g = 0; $g < count($t_g_f); $g++){
            for ($d = 0; $d < count($t_d_f); $d++){
                if ($t_g_f[$g]['name']==$t_d_f[$d]['COLUMN_NAME']){
                    $temp_different = $this->comparison_field($t_g_f[$g],$t_d_f[$d]);
                    if ($temp_different!==null){
                        array_push($different_field,$temp_different);
                    }
                    array_splice($t_g_f,$g,1);
                    array_splice($t_d_f,$d,1);
                    $g--;
                    break;
                }
            }
        }
        $g_null = $t_d_f;
        $d_null = $t_g_f;

        $res['g_null'] = array();
        foreach ($g_null as $k => $v){
            array_push($res['g_null'],$this->change_data_structure($v,$table_id));
        }

        $res['d_null'] = $d_null;
        $res['different_field'] = $different_field;
        return $res;
    }
    //单条字段比较
    public function comparison_field($generate_field,$database_field){
        $g_f = $generate_field;
        $d_f = $database_field;
        
        $different = false;
        //类型判断
        if (strtolower($g_f['type'])!==$d_f['DATA_TYPE']){
            $different = true;
        }
        //长度判断（值）
        if ($g_f['type']!=="Text" && $g_f['type']!=="Date"){
            $d_length = str_replace($d_f['DATA_TYPE'],'',str_replace(')','',str_replace('(','',str_replace('\'','',$d_f['COLUMN_TYPE']))));
            if ($g_f['type']!=="Enum"){
                if ($g_f['length']!=$d_length){
                    $different = true;
                }
            }else{
                if (!empty(array_diff(explode(',',$g_f['length']),explode(',',$d_length)))){
                    $different = true;
                }
            }
        }
        //备注判断（comment）
        if ($g_f['comment']!=explode('（',explode('(',$d_f['COLUMN_COMMENT'])[0])[0]){
            $different = true;
        }
        //判断是否允许空（not_null）
        if ($g_f['not_null']!=($database_field['IS_NULLABLE']=='YES'?0:1)){
            $different = true;
        }
        //如果不是generate枚举中的类型就不进行记录
        $d_f_name = $this->change_name($database_field['DATA_TYPE']);
        if (empty($d_f_name)){
            $different = false;
        }


        //根据是否相同返回结果
        if ($different){
            $res['generate'] = $generate_field;
            $res['database'] = $this->change_data_structure($database_field,$generate_field['table_id'],$generate_field['id']);
        }else{
            $res = null;
        }
        return $res;
    }

    //database转换为generate字段格式
    public function change_data_structure($database_field,$table_id,$id=null){
        $d_f_name = $this->change_name($database_field['DATA_TYPE']);
        if (empty($d_f_name)){
            return null;
        }
        $res = [
            'id' => $id,
            'table_id' => $table_id,
            'comment' => explode('（',explode('(',$database_field['COLUMN_COMMENT'])[0])[0],
            'name' => $database_field['COLUMN_NAME'],
            'type' => $d_f_name,
            'length' => $this->get_length($database_field),
            'default' => $this->get_default($database_field),
            'not_null' => $database_field['IS_NULLABLE']=='YES'?0:1,
            'enum' => json_encode([])
        ];
        if ($id==null){
            unset($res['id']);
        }
        return $res;
    }

    //名字转换
    public function change_name($field_name){
        if ($field_name=='enum'){
            return 'Enum';
        }else if($field_name=='varchar'){
            return 'VarChar';
        }else if($field_name=='int'){
            return 'Int';
        }else if($field_name=='tinyint'){
            return 'TinyInt';
        }else if($field_name=='decimal'){
            return 'Decimal';
        }else if($field_name=='text'){
            return 'Text';
        }else if($field_name=='date'){
            return 'Date';
        }else{
            return null;
        }
    }
    //获取数据中字段的长度
    public function get_length($database_field){
        if ($database_field['DATA_TYPE']=='text'){
            return '';
        }
        $res = str_replace($database_field['DATA_TYPE'].'(','',$database_field['COLUMN_TYPE']);
        $res = str_replace(')','',$res);
        $res = str_replace('\'','',$res);
        return $res;
    }
    //获取数据中字段的默认值
    public function get_default($database_field){
        if ($database_field['EXTRA']!==''){
            return strtoupper($database_field['EXTRA']);
        }
        if ($database_field['COLUMN_DEFAULT']!==null){
            return $database_field['COLUMN_DEFAULT'];
        }
        return '';
    }

    //删除generate字段（批量）
    public function delete_field_list($id_data){
        return Db::table('zb_generate.tp_field')->delete($id_data);
    }
    //添加database字段（批量）
    public function add_field_to_database($db_mame,$table_name,$field_list){
        $api_model = new \app\generate\model\Api();
        $count_res = 0;
        foreach ($field_list as $k=>$v){
            $res = $api_model->alter_table_add($db_mame,$table_name,$v);
            if ($res){
                $count_res++;
            }
        }
        return $count_res;
    }
    //删除database字段（批量）
    public function del_field_to_database($db_mame,$table_name,$field_list){
        $api_model = new \app\generate\model\Api();
        $count_res = 0;
        foreach ($field_list as $k=>$v){
            $res = $api_model->alter_table_drop($db_mame,$table_name,$v['name']);
            if ($res){
                $count_res++;
            }
        }
        return $count_res;
    }

    //修改comment字段
    public function edit_field_comment($db_mame,$table_name,$field){
        $database_field = $database_field = Db::table('INFORMATION_SCHEMA.Columns')->where([['TABLE_NAME','=',$table_name],['COLUMN_NAME','=',$field['name']]])->find();
        $field_name = $database_field['COLUMN_TYPE'];
        $not_null = "";
        if ($field['not_null']){
            $not_null = " NOT NULL";
        }

        $query = "ALTER TABLE ".$table_name." MODIFY COLUMN ".$field['name']." ".$field_name." COMMENT '".$field['comment']."'".$not_null;

        return $this->pdo_exec_sql($query,$db_mame)!==false;

    }
}